﻿using System;
using System.Net;
using TestApp.WebService.Parsers;
using TestApp.Model.Data;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace TestApp.WebService
{
    public sealed class StoresService
    {
        private static volatile StoresService instance;
        private static object syncRoot = new Object();

        private StoresService() { }

        // Singleton Instance
        public static StoresService Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new StoresService();
                    }
                }

                return instance;
            }
        }

        public async Task<List<Store>> SearchStoresByZip(String zipCode)
        { 
            // Set the URL
            string URL = @"https://mws2.qa2.mywebgrocer.com/stores/2.2.0.27/chain/139/postalCode/{zipcode}/radius/20/unit/Miles/page/1/size/32767?mwgservice=Shop2Gro";
            URL = URL.Replace("{zipcode}", zipCode);
            string authorization = @"0F8C1EE4-9253-446C-87B2-B0A04A70A25A";

            // Get The Response
            WSResponse response = await WSManager.Instance.ExecuteRequest(HttpMethod.GET, URL, null, authorization, null, HttpHeader.ApplicationJsonContentType).ConfigureAwait(false);

            // Create the parser and hanlde the response data
            Parser parser = new StoresParser();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                // Success
                return parser.ParseResults(response) as List<Store>;
            }
            else
            {
                // Throw WSException
                throw parser.ParseError(response);
            }
        }
    }
}
